<?php

namespace App\Http\Controllers\Finance;

use App\Common\Traits\Model\ModelSearchTrait;
use App\Helpers\ServiceTrait;
use App\Http\Controllers\Controller;
use App\Jobs\Finance\Traits\CommonBillTrait;
use App\Jobs\Finance\Traits\CommonBranchBillTrait;
use App\Jobs\Finance\Traits\CreateBillTrait;
use App\Jobs\Finance\Traits\FinanceBranchBillTrait;
use App\Models\Finance\FinanceBranchBill;
use App\Models\Finance\FinanceBranchDetailBill;
use App\Models\Finance\FinanceCustomerBill;
use App\Models\Finance\FinanceShopSubAccountBill;
use Illuminate\Http\Request;
use App\Jobs\Finance\FinanceBillJob;

class FinanceBranchBillController extends Controller
{
    use ModelSearchTrait, ServiceTrait, FinanceBranchBillTrait,CommonBranchBillTrait, CreateBillTrait, CommonBillTrait;

    //分部账单列表
    public function branchBillList(Request $request,FinanceBranchBill $branchBill){
        $user=$request->user();
        if($user->department_one_id!=3 || $user->department_id==$user->department_two_id){
            $branchBill=$this->model($branchBill,$user);
        }else{
            //普通客服，隶属于3级部门
            $branchBill=$branchBill->where('department_id',$user->department_two_id);
        }
        $branchBill=$this->singleModelSearch($request,$branchBill,$this->listCondition());
        $bills=$branchBill->with(['customerBill'])->orderByDesc('id')->paginate($this->size??20);
        return $this->success($bills);
    }
    public function listCondition(){
        return [
            ['bill_status','='],
            ['bill_date','='],
        ];
    }

    //分部账单详情
    public function branchBillDetail(Request $request){
        $branchBill=FinanceBranchBill::with(['customerBill','billDetail'])->find($request->branch_bill_id??0);
        return $this->success($branchBill);
    }

    //更新报价分组数据
    public function updateBranchGroupTotal($branchBill){
        $detailBills=$branchBill->billDetail;
        $this->shopGroupPrice=[];
        foreach ($detailBills as $detail){
            $groupTotal=$this->getGroupConsultTotal($detail);
            $dayAverage=$detail->total_quote_consult_days?round($groupTotal/$detail->total_quote_consult_days,1):0;
            $data=[
                'quote_total_consult'=>$groupTotal,
                'quote_day_average_consult'=>$dayAverage,
                'service_quote_final'=>$this->selectQuoteFinal($detail->service_price,$dayAverage),
            ];
            $detail->update($data);
            //设置店铺分组数据
            $this->getShopGroupPrice($detail);
        }
        //分部账单店铺管理费
        $this->updateShopGroupTotal();
    }
    //组合店铺分组数据
    public function getShopGroupPrice($detail){
        $this->shopGroupPrice[$detail->shop_id]['sub_bill_ids'][]=$detail->id;
        $this->shopGroupPrice[$detail->shop_id]['sub_bill_consult'][]=$detail->consult_quantity;
        $this->shopGroupPrice[$detail->shop_id]['service_price']=$detail->service_price;
        $this->shopGroupPrice[$detail->shop_id]['group_start_end'][]=$this->getBranchServicePeriod($detail->service_period);
    }
    //获取按报价分组的总咨询量
    public function getGroupConsultTotal($detail){
        return FinanceBranchDetailBill::where('department_quote_id',$detail->department_quote_id)
            ->where('branch_bill_id',$detail->branch_bill_id)
            ->sum('consult_quantity');
    }

    //更新分部总账单
    public function branchBillUpdate(Request $request){
        $branchBill=FinanceBranchBill::find($request->branch_bill_id??0);
        if(empty($branchBill)){
            return $this->failed('账单id错误，无此账单');
        }
        $data=$request->except('branch_bill_id');
        $branchBill->update($data);
        if($request->filled('bill_status') && $request->bill_status==3){
            if($branchBill->is_reassign_bill==0){
                $this->dataToCustomerBill($branchBill);
            }
        }
        return $this->success('更新成功');
    }

    //更新分部账单详情
    public function UpdateBranchBillAccount(Request $request){
        $billAccount=FinanceBranchDetailBill::find($request->bill_account_id??0);
        if(empty($billAccount)){
            return $this->failed('账单id错误，无此账单');
        }
        $data=$request->except('bill_account_id');
        $billAccount->update($data);
        $branchBillData=$this->sumBranchBillData($billAccount);
        $billAccount->branchBill()->update($branchBillData);
        $branchBill=$billAccount->branchBill;
        $this->updateBranchGroupTotal($branchBill);
        return $this->success('更新成功');
    }
    //分部账单总量统计
    public function sumBranchBillData($billAccount){
        $branchDetail=FinanceBranchDetailBill::where('branch_bill_id',$billAccount->branch_bill_id);
        return [
            'total_service_days'=>$branchDetail->sum('service_days'),
            'total_consult'=>$branchDetail->sum('consult_quantity'),
            'total_pay_branch'=>$branchDetail->sum('pay_amount'),
        ];
    }

    //分部数据同步至客户账单
    public function dataToCustomerBill($branchBill){
        $customerBill=$branchBill->customerBill;
        $this->syncCustomerBillData($branchBill,$customerBill);
        if($this->checkAllPass($branchBill)){
            $customerBill->data_fill_status=1;
            $customerBill->save();
        }
    }
    //分部账单是否都通过了审核
    public function checkAllPass($branchBill){
        $branchBills=FinanceBranchBill::where('customer_bill_id',$branchBill->customer_bill_id)->get();
        if(count($branchBills)){
            foreach ($branchBills as $bill){
                if($bill->bill_status<3){
                    return false;
                }
            }
        }
        return true;
    }
    //数据同步至客户账单详情
    public function syncCustomerBillData($branchBill,$customerBill){
        $detailBills=$branchBill->billDetail;
        foreach ($detailBills as $detail){
            $data=[
                'service_days'=>$detail->service_days,
                'consult_quantity'=>$detail->consult_quantity,
                'shop_other_fee'=>$detail->shop_other_fee,
                'data_fill_status'=>1,
            ];
            $detail->subAccountBill()->update($data);
        }
        $this->updateCustomerBillTotal($customerBill);
    }
    //客户账单总量统计更新
    public function updateCustomerBillTotal($customerBill){
        $this->updateCustomerGroupTotal($customerBill);
        $cbData=[
            'total_service_days'=>$customerBill->accountBills()->sum('service_days'),
            'total_consult'=>$customerBill->accountBills()->sum('consult_quantity'),
        ];
        $customerBill->update($cbData);
        //更新本期费用合计，应收客户金额之类的汇总数据
        $this->calcUpdateCustomerBillTotal($customerBill);
    }
    //更新报价分组数据
    public function updateCustomerGroupTotal($customerBill){
        $accountBills=$customerBill->accountBills;
        foreach ($accountBills as $account){
            $groupTotal=$this->getGroupCustomerTotal($account);
            $dayAverage=$account->total_quote_consult_days?round($groupTotal/$account->total_quote_consult_days,1):0;
            $data=[
                'quote_total_consult'=>$groupTotal,
                'quote_day_average_consult'=>$dayAverage,
                'service_quote_final'=>$this->getCustomerQuotePrice($account,$groupTotal),
            ];
            $account->update($data);
        }
    }
    public function getGroupCustomerTotal($account){
        return FinanceShopSubAccountBill::where('bill_id',$account->bill_id)
            ->where('quotation_group_id',$account->quotation_group_id)
            ->sum('consult_quantity');
    }
    //
    public function getCustomerQuotePrice($account,$dayAverage){
        if($account->shop && $account->shop->quotaionInfo && $account->shop->quotaionInfo->priceRange){
            $final=0;
            foreach ($account->shop->quotaionInfo->priceRange as $range){
                if($dayAverage>=$range->min && $dayAverage<$range->max){
                    return $range->price;
                }
                //匹配不上就用最后一行的
                $final=$range->price;
            }
            return $final;
        }
        return 0;
    }


}
